﻿using AutoMapper;
using B.S.DataBase.Domain;
using B.S.DataBase.ErrorCode;
using B.S.DataBase.Infrastructure;
using B.S.DataBase.Write.API.Application.Commands.Update;
using MediatR;

namespace B.S.DataBase.Write.API.Application.Handlers.UpdateHandler
{
    public class UpdateProductHandler : IRequestHandler<UpdateProductCommand, APIResult<int>>
    {
  
        private readonly IBaseRepository<Product> proudctRepository;
        private readonly IMapper mapper;

        public UpdateProductHandler(IBaseRepository<Product> proudctRepository, IMapper mapper)
        {
            this.proudctRepository = proudctRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(UpdateProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var enitty = proudctRepository.GetAllAsync().FirstOrDefault(x=>x.Id==request.Id);
            if (enitty !=null)
            {
                enitty.ProductId = request.ProductId;
                enitty.BatchId = request.BatchId.ToString();
                enitty.KeepSafe = request.KeepSafe;
                enitty.Permission = request.Permission;
                enitty.FirmName = request.FirmName;
                var dto = proudctRepository.Update(enitty).Result;
                if (dto > 0)
                {
                    result.Code = APIEnums.Success;
                    result.Meg = "修改成功";
                    result.Data = dto;
                }
            }
            else
            {
                result.Code = APIEnums.Fail;
                result.Meg = "修改失败";
                return await Task.FromResult(result);
            }
            return await Task.FromResult(result);
        }
    }
}
